/**
 * Created by liyun on 2015/10/28.
 */
var knex = require('../utils/knex');
var Promise = require('bluebird');
var debug = require('debug')('models:orders');
var orders = function(){
    if(typeof this.list !='function'){
        orders.prototype.list = function(page,callback){

            countOrders(function(count){
                knex.select(knex.raw('shop_goods.title,shop_goods.thumb,shop_goods.productprice,dispatch.name,' +
                    'joininfo.id,joininfo.dispatchNum,joininfo.term,joininfo.lottery,joininfo.count,joininfo.address,date_format(shop_goods_term.createtime,"%Y-%m-%d %H:%i:%s") as createtime')).from('shop_goods').innerJoin('shop_goods_term',function(){
                 this.on('shop_goods.id','=','shop_goods_term.gid');
                 }).innerJoin('joininfo',function(){
                 this.on('joininfo.sgtid','=','shop_goods_term.id');
                 }).leftJoin('dispatch',function(){
                 this.on('dispatch.id','=','joininfo.dispatchid');
                 }).orderBy(page[0], page[1])
                    .limit(page[3]).offset(page[2])
                    .then(function(data){
                        callback({total:count[0].count,rows:data});
                    }).catch(function(err){
                        callback(err);
                    });
            });
        }

    }
    if(typeof this.edit !='function') {
        orders.prototype.edit = function (body, callback) {
            knex('joininfo')
                .where('id', '=', body.id)
                .update(body).then(function(data){
                    callback({msg:true});
                }).catch(function(err){
                    callback({msg:false});
                });

        }
    }
}




function countOrders(callback){
    /*knex('activity').count('id as count')
     .then(function(data){
     callback(data);
     }).catch(function(err){
     callback(err);
     });*/

    knex.count('shop_goods.id as count').from('shop_goods').innerJoin('shop_goods_term',function(){
        this.on('shop_goods.id','=','shop_goods_term.gid');
    }).innerJoin('joininfo',function(){
        this.on('joininfo.sgtid','=','shop_goods_term.id');
    }).then(function(data){
        debug('countshop_goods_term');
        debug(data);
        debug('countshop_goods_term');
        callback(data);
    }).catch(function(err){
        callback(err);
    });
}

module.exports.orders = orders;